package cc.linker.steplink.crm.service.impl;

import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.dao.SurvivalDao;
import cc.linker.steplink.crm.merchant.dao.EnrollDao;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchant.service.SurvivalPcService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.ISurvivalService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class SurvivalServiceImpl implements ISurvivalService {

    @Autowired
    private SurvivalDao survivalDao;

    @Autowired
    private ShopGoodsMapper shopGoodsMapper;

    @Autowired
    private EnrollDao enrollDao;

    @Autowired
    private HttpService httpService;

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private SurvivalPcService survivalPcService;

    @Override
    public void AddSurvival(Map<String, Object> map) {
        String survivalId = StringUtils.isEmpty(map.get("id"))?UUID.randomUUID().toString():map.get("id").toString();

        Map<String,Object> survivalMap = new HashMap<>();
        List<Map<String,Object>> survivalContentMap = new ArrayList<>();
        List<Map<String,Object>> survivalContentValueMap = new ArrayList<>();
        survivalMap.put("id",survivalId);
        survivalMap.put("title",map.get("title"));
        survivalMap.put("trigger",map.get("trigger"));
        survivalMap.put("expirationTime",map.get("expirationTime"));
        survivalMap.put("startTime",map.get("startTime"));
        survivalMap.put("endTime",map.get("endTime"));
        survivalMap.put("canRepeat",map.get("canRepeat"));
        survivalMap.put("orgId",map.get("orgId"));
        survivalMap.put("articleIds",map.get("articleIds"));
        if(!StringUtils.isEmpty(map.get("menuId"))){
            survivalMap.put("menuId",map.get("menuId"));
        }
        if(!StringUtils.isEmpty(map.get("eventKey"))){
            survivalMap.put("eventKey",map.get("eventKey"));
        }
        //
        List<Map<String,Object>> contents = (List) map.get("contents");
        for (int i = 0; i < contents.size(); i++) {
            String contentId = UUID.randomUUID().toString();
            Map<String,Object> content = new HashMap<>();
            content.put("id",contentId);
            content.put("survivalId",survivalId);
            content.put("sendTime",contents.get(i).get("sendTime"));
            content.put("type",contents.get(i).get("type"));
            content.put("sort",contents.get(i).get("sort"));
            survivalContentMap.add(content);
            //
            List<String> contentValues = (List) contents.get(i).get("contentValues");
            for (int j = 0; j < contentValues.size(); j++) {
                Map<String,Object> contentValue = new HashMap<>();
                contentValue.put("survivalId",survivalId);
                contentValue.put("contentId",contentId);
                contentValue.put("value",JSON.toJSONString(contentValues.get(j)));
                survivalContentValueMap.add(contentValue);
            }
        }
        if(StringUtils.isEmpty(map.get("id"))){
            // 新增
            survivalDao.addSurvival(survivalMap);
            survivalDao.addSurvivalContent(survivalContentMap);
            survivalDao.addSurvivalContentValue(survivalContentValueMap);
        }else{
            // 编辑
            survivalDao.deleteSurvivalContent(survivalId);
            survivalDao.deleteSurvivalContentValue(survivalId);
            survivalDao.updateSurvival(survivalMap);
            survivalDao.addSurvivalContent(survivalContentMap);
            survivalDao.addSurvivalContentValue(survivalContentValueMap);
        }
    }

    @Override
    public void delSurvival(Map<String, Object> map){
        survivalDao.deleteSurvival(map);
    }

    @Override
    public void stopSurvival(Map<String, Object> map){
        survivalDao.stopSurvival(map);
    }

    @Override
    public List<Map<String, Object>> getList(Map<String, Object> param){
        return survivalDao.getList(param);
    }

    @Override
    public Map<String, Object> getDetail(Map<String, Object> param){
        Map<String, Object> detail = survivalDao.getDetail(param);
        if(null == detail){
            throw GlobalException.build("参数错误");
        }
        List<Map<String, Object>> userTouchList = new ArrayList<>();
        List<Map<String, Object>> userSurvivalList = new ArrayList<>();
        Date today = new Date();
        //获取三十天前日期
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(today);
        theCa.add(Calendar.DATE, -30);//30天前
        Date start = theCa.getTime();
        List<String> dates = findDates(start, today);
        for(String da:dates){
            Map<String, Object> userTouchMap = new HashMap<>();
            Map<String, Object> userSurvivalMap = new HashMap<>();
            String startTime = da + " 00:00:00";
            String endTime = da + " 23:59:59";
            param.put("startTime",startTime);
            param.put("endTime",endTime);
            Integer userTouch = survivalDao.getUserTouch(param);
            userTouchMap.put("dateTime",da);
            userTouchMap.put("num",userTouch);
            Integer userSurvival = survivalDao.userSurvival(param);
            userSurvivalMap.put("dateTime",da);
            userSurvivalMap.put("num",userSurvival);
            userTouchList.add(userTouchMap);
            userSurvivalList.add(userSurvivalMap);
        }
        detail.put("userTouchList",userTouchList);
        detail.put("userSurvivalList",userSurvivalList);
        return detail;
    }

    @Override
    public Map<String, Object> getInfo(Map<String, Object> param)
    {
        Map<String, Object> info = survivalDao.getInfo(param);
        List<Map<String,Object>> articleList = new ArrayList<>();
        String articleIds = StringUtils.isEmpty(info.get("articleIds"))?null:info.get("articleIds").toString();
        if(articleIds!=null){
            String[] split = articleIds .split(",");
            for (String articleId : split){
                try {
                    articleList.add(this.getArticleById(articleId));
                } catch (Exception e) {
                    break;
                }
            }
        }
        // 查询关联的文章
        info.put("articleList",articleList);
        // 获取内容
        List<Map<String,Object>> contents = survivalDao.getContents(param);
        for (int i = 0; i < contents.size(); i++) {
            Map<String,Object> x = contents.get(i);
            List<Map<String,Object>> contentValues = survivalDao.getContentValues(x.get("id").toString());
            int type = Integer.parseInt(x.get("type").toString());
            List<Map<String,Object>> listValues = new ArrayList<>();
            contentValues.forEach(c->{
                Map<String,Object> value = JSON.parseObject(c.get("value").toString());
                // todo
                switch (type){
                    case 5:
                    case 6:
                    case 13:
                    case 14:
                        // 商品
                        Map<String, Object> goodsInfo = this.getGoodsById(value.get("goodsId").toString());
                        if(goodsInfo==null){
                            break;
                        }
                        listValues.add(goodsInfo);
                        break;
                    case 7:
                    case 15:
                        // 文章
                        try {
                            listValues.add(this.getArticleById(value.get("articleId").toString()));
                        } catch (Exception e) {
                            break;
                        }
                        break;
                    case 8:
                    case 16:
                        // 报名
                        Map<String, Object> enrollInfo = this.getEnrollInfo(value.get("enrollId").toString());
                        if(enrollInfo==null){
                            break;
                        }
                        listValues.add(enrollInfo);
                        break;
                    default:
                        listValues.add(value);
                }
            });
            x.put("contentId",x.get("id"));
            x.remove("id");
            x.put("contentValues",listValues);
            if(listValues.isEmpty()){
                contents.remove(x);
            }
        };
        info.put("contents",contents);
        return info;
    }

    private Map<String, Object> getEnrollInfo(String enrollId) {
        Map<String,Object> enrollInfo =survivalDao.getEnrollById(enrollId);
        if(enrollInfo==null){
            return null;
        }
        int finalStatus = enrollInfo.get("status") == null ? 0 : Integer.parseInt(enrollInfo.get("status").toString());
        Long price = enrollDao.getMinprice(enrollId);
        enrollInfo.put("price", NumberUtils.fenToYuan(price));
        if (finalStatus > 0) {
            switch (finalStatus) {
                case 1:
                    enrollInfo.put("statusName", "待报名");
                    break;
                case 2:
                    enrollInfo.put("statusName", "报名中");
                    break;
                case 3:
                    enrollInfo.put("statusName", "报名结束");
                    break;
                case 4:
                    enrollInfo.put("statusName", "报名已满");
                    break;
                default:
                    enrollInfo.put("statusName", "报名关闭");
                    break;
            }
        } else {
            // 判断状态
            String startTime = enrollInfo.get("startTime") == null ? "" : enrollInfo.get("startTime").toString();
            String endTime = enrollInfo.get("endTime") == null ? "" : enrollInfo.get("endTime").toString();
            String status = enrollInfo.get("status").toString();
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime = sdf.format(d);
            // 获取已报名人数
            Integer realNum = enrollDao.getRealNum(enrollId);
            // 获取设置的报名总人数 减去 初始化的总人数
            Integer setNum = enrollDao.getSetNum(enrollId);
            // 获取是否存在不限人数的报名项
            Integer unlimited = enrollDao.unlimited(enrollId);
            if ("0".equals(status)) {
                enrollInfo.put("statusName", "报名关闭");
            } else if (!StringUtils.isEmpty(startTime) && nowTime.compareTo(startTime) < 0) {
                // 待报名
                enrollInfo.put("statusName", "待报名");
            } else if (!StringUtils.isEmpty(endTime) && nowTime.compareTo(endTime) > 0) {
                // 报名结束
                enrollInfo.put("statusName", "报名结束");
            } else if (unlimited < 1 && realNum >= setNum) {
                // 报名已满
                enrollInfo.put("statusName", "报名已满");
            } else {
                //报名中
                enrollInfo.put("statusName", "报名中");
            }
        }
        List<Map<String,Object>> labels = enrollDao.getEnrollLabelsById(enrollId);
        enrollInfo.put("labels",labels);
        return enrollInfo;
    }

    private Map<String, Object> getGoodsById(String id) {
        Map<String,Object> goodsInfo =survivalDao.getGoodsById(id);
        if(goodsInfo==null){
            return null;
        }
        goodsInfo.put("labels",shopGoodsMapper.getGoodsLabelsById(Long.parseLong(goodsInfo.get("goodsId").toString())));
        return goodsInfo;
    }

    private Map<String,Object> getArticleById(String articleId) throws Exception {
        String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_DETAIL;
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> resData = new HashMap<>();
        param.put("newsId", articleId);
        JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
        String postres = httpService.doPost(url, jsonObject.toJSONString(), ContentConstant.JSON_HEADER);
        LOGGER.info("getarticledetail===result===" + postres);
        if (null != postres) {
            Map res = (Map) JSON.parse(postres);
            if ("200".equals(res.get("code").toString())) {
                if (res.get("data") == null) {
                    throw GlobalException.build("暂无文章数据");
                }
                resData.putAll((Map) res.get("data"));
//                resData.put("newsName", ((Map) res.get("data")).get("newsName"));
//                resData.put("createTime", ((Map) res.get("data")).get("createTime"));
//                resData.put("newsSummary", ((Map) res.get("data")).get("newsSummary"));
//                resData.put("newsContent", ((Map) res.get("data")).get("newsContent"));
//                resData.put("headPicUrl", ((Map) res.get("data")).get("headPicUrl"));
//                resData.put("newsCover", ((Map) res.get("data")).get("newsCover"));
            } else {
                throw GlobalException.build("请求失败");
            }
        } else {
            throw GlobalException.build("请求失败");
        }
        return resData;
    }

    @Override
    public Integer getRepeatTitle(Map<String, Object> map)
    {
        return survivalDao.getRepeatTitle(map);
    }

    @Override
    public List getMenuList(Map<String, Object> map) {
        return survivalDao.getMenuList(map);
    }

    @Override
    public List getMenuDataList(Long menuId) {
        String menuDataString = survivalDao.getMuneDataList(menuId);
        List menuDataList = new ArrayList();
        if(!StringUtils.isEmpty(menuDataString)){
            Map object = JSON.parseObject(menuDataString,Map.class);
            if(!StringUtils.isEmpty(object.get("button"))){
                List<Map> menuDataListO = JSONArray.parseArray(object.get("button").toString(),Map.class);
                for (Map menuMap : menuDataListO){
                    Map maps = new HashMap();
                    if(menuMap.containsKey("sub_button") && !StringUtils.isEmpty(menuMap.get("sub_button"))){
                        //有二级菜单
                        String subButton = menuMap.get("sub_button").toString();
                        List subButtonList = new ArrayList();
                        List<Map> subButtonListO = JSONArray.parseArray(subButton,Map.class);
                        for(Map subButtonMap : subButtonListO){
                            Map subButtonMaps = new HashMap();
                            if(!StringUtils.isEmpty(subButtonMap.get("key"))){
                                //只需要clickPushEvent类型的
                                if(subButtonMap.get("key").toString().contains("clickPushEvent")){
                                    subButtonMaps.put("name",subButtonMap.get("name"));
                                    subButtonMaps.put("eventKey",subButtonMap.get("key"));
                                    subButtonMaps.put("level",2);
                                }
                            }
                            if (subButtonMaps.size()>0){
                                subButtonList.add(subButtonMaps);
                            }
                        }
                        if(subButtonList.size()>0){
                            maps.put("name",menuMap.get("name"));
                            maps.put("subButtonList",subButtonList);
                            maps.put("eventKey","");
                            maps.put("level",1);
                        }
                    }else {
                        //无二级菜单
                        if(!StringUtils.isEmpty(menuMap.get("key"))){
                            //只需要clickPushEvent类型的
                            if(menuMap.get("key").toString().contains("clickPushEvent")){
                                maps.put("name",menuMap.get("name"));
                                maps.put("eventKey",menuMap.get("key"));
                                maps.put("level",1);
                            }
                        }
                    }
                    if (maps.size()>0){
                        menuDataList.add(maps);
                    }
                }
            }
        }
        return menuDataList;
    }

    /**
     * 根据菜单id删除促活
     * @param menuId
     */
    @Override
    public void deleteByMenuId(Long menuId) {
        survivalPcService.deleteByMenuId(menuId);
    }


    public static List<String> findDates(Date dBegin, Date dEnd) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> lDate = new ArrayList<>();
//        lDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            String strDate = sdf.format(calBegin.getTime());
            lDate.add(strDate);
        }
        return lDate;
    }
}
